<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import { addJueSeApi } from '@/api/system'

const emit = defineEmits<{
  (e: 'getJueSeWeiHuFn'): void
}>()

const ruleFormRef = ref<FormInstance>()
const addJueSeVisible = ref(false)
interface RuleForm {
  role_id: string
  role_name: string
  remark: string
}

const form = ref({
  EXIST: 0,
  role_id: '',
  role_name: '',
  remark: ''
})

const rules = reactive<FormRules<RuleForm>>({
  role_id: [{ required: true, message: '请输入角色ID', trigger: 'blur' }],
  role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
})

const addJueSeFn = async () => {
  const params = {
    sqlId: JSON.stringify(['roleMgr.insertRole']),
    sqlParam: JSON.stringify([
      {
        ...form.value
      }
    ]),
    dbName: undefined
  }
  await addJueSeApi(params)
    .then((res: any) => {
      // console.log(res)
      if (res === 'success') {
        emit('getJueSeWeiHuFn')
        ElMessage({ message: '添加成功', type: 'success' })
      } else {
        ElMessage({ message: '添加失败', type: 'error' })
      }
    })
    .catch(() => {
      ElMessage({ message: '添加失败', type: 'error' })
    })
}
const Confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      addJueSeFn()
    } else {
      ElMessage({ message: '请输入完整信息', type: 'error' })
    }
  })
  addJueSeVisible.value = false
}
const Cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  addJueSeVisible.value = false
}

defineExpose({
  addJueSeVisible
})
</script>

<template>
  <div class="addJueSeBox">
    <el-dialog v-model="addJueSeVisible" title="添加角色" width="500">
      <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="auto">
        <el-form-item label="角色ID" prop="role_id">
          <el-input v-model="form.role_id" />
        </el-form-item>
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="form.role_name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="remark">
          <el-input v-model="form.remark" :rows="4" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Cancel(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="Confirm(ruleFormRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less"></style>
